<?php
session_start();

// 配置设置
define('UPLOAD_DIR', 'uploads/');
define('DATA_DIR', 'data/');
define('MAX_FILE_SIZE', 50 * 1024 * 1024); // 50MB
define('EXPIRE_TIME', 24 * 3600); // 24小时

// 创建必要目录
if (!file_exists(UPLOAD_DIR)) mkdir(UPLOAD_DIR, 0755, true);
if (!file_exists(DATA_DIR)) mkdir(DATA_DIR, 0755, true);

// 清理过期文件
cleanupExpiredFiles();

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    handleFormSubmission();
}

// 处理提取请求
if (isset($_GET['code'])) {
    handleRetrieval();
}

/**
 * 清理过期文件
 */
function cleanupExpiredFiles() {
    $files = glob(DATA_DIR . '*.json');
    $now = time();
    
    foreach ($files as $file) {
        $data = json_decode(file_get_contents($file), true);
        if ($data && isset($data['expires']) && $data['expires'] < $now) {
            unlink($file);
            if ($data['type'] === 'file' && file_exists($data['file_path'])) {
                unlink($data['file_path']);
            }
        }
    }
}

/**
 * 处理表单提交
 */
function handleFormSubmission() {
    $type = $_POST['type'] ?? '';
    $code = generateUniqueCode();
    
    if ($type === 'text') {
        $content = $_POST['text_content'] ?? '';
        if (empty($content)) {
            $_SESSION['error'] = "文本内容不能为空";
            header("Location: " . $_SERVER['PHP_SELF']);
            exit;
        }
        
        saveContent($code, [
            'type' => 'text',
            'content' => $content,
            'created' => time(),
            'expires' => time() + EXPIRE_TIME
        ]);
        
        $_SESSION['success'] = "文本内容已保存！提取码: <strong>$code</strong>";
        $_SESSION['code'] = $code;
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    } 
    elseif ($type === 'file') {
        if (!isset($_FILES['file_upload']) || $_FILES['file_upload']['error'] !== UPLOAD_ERR_OK) {
            $_SESSION['error'] = "文件上传失败";
            header("Location: " . $_SERVER['PHP_SELF']);
            exit;
        }
        
        $file = $_FILES['file_upload'];
        if ($file['size'] > MAX_FILE_SIZE) {
            $_SESSION['error'] = "文件大小超过限制 (最大50MB)";
            header("Location: " . $_SERVER['PHP_SELF']);
            exit;
        }
        
        $filename = preg_replace('/[^a-zA-Z0-9\.\-_]/', '', $file['name']);
        $filepath = UPLOAD_DIR . $code . '_' . $filename;
        
        if (!move_uploaded_file($file['tmp_name'], $filepath)) {
            $_SESSION['error'] = "文件保存失败";
            header("Location: " . $_SERVER['PHP_SELF']);
            exit;
        }
        
        saveContent($code, [
            'type' => 'file',
            'file_name' => $filename,
            'file_path' => $filepath,
            'file_size' => $file['size'],
            'created' => time(),
            'expires' => time() + EXPIRE_TIME
        ]);
        
        $_SESSION['success'] = "文件已上传！提取码: <strong>$code</strong>";
        $_SESSION['code'] = $code;
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }
}

/**
 * 处理提取请求
 */
function handleRetrieval() {
    $code = strtoupper(trim($_GET['code']));
    $dataFile = DATA_DIR . $code . '.json';
    
    if (!file_exists($dataFile)) {
        $_SESSION['error'] = "无效的提取码或内容已过期";
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }
    
    $data = json_decode(file_get_contents($dataFile), true);
    if (!$data) {
        $_SESSION['error'] = "数据读取失败";
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }
    
    if ($data['expires'] < time()) {
        unlink($dataFile);
        if ($data['type'] === 'file' && file_exists($data['file_path'])) {
            unlink($data['file_path']);
        }
        $_SESSION['error'] = "内容已过期";
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }
    
    if ($data['type'] === 'text') {
        $_SESSION['retrieved_text'] = $data['content'];
        $_SESSION['success'] = "文本内容提取成功";
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    } 
    elseif ($data['type'] === 'file') {
        $filepath = $data['file_path'];
        $filename = $data['file_name'];
        
        if (!file_exists($filepath)) {
            $_SESSION['error'] = "文件不存在";
            header("Location: " . $_SERVER['PHP_SELF']);
            exit;
        }
        
        // 提供文件下载
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filepath));
        readfile($filepath);
        exit;
    }
}

/**
 * 保存内容数据
 */
function saveContent($code, $data) {
    $filename = DATA_DIR . $code . '.json';
    return file_put_contents($filename, json_encode($data), LOCK_EX) !== false;
}

/**
 * 生成唯一提取码
 */
function generateUniqueCode($length = 6) {
    $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // 避免易混淆字符
    $code = '';
    
    do {
        $code = '';
        for ($i = 0; $i < $length; $i++) {
            $code .= $chars[rand(0, strlen($chars) - 1)];
        }
    } while (file_exists(DATA_DIR . $code . '.json'));
    
    return $code;
}

/**
 * 格式化文件大小
 */
function formatFileSize($bytes) {
    if ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    } else {
        return $bytes . ' bytes';
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>匿名口令分享系统</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            color: #333;
            line-height: 1.6;
            min-height: 100vh;
            padding: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .container {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            width: 100%;
            max-width: 800px;
            padding: 30px;
            margin: 20px;
        }
        
        header {
            text-align: center;
            margin-bottom: 30px;
        }
        
        h1 {
            color: #2c3e50;
            font-size: 2.5rem;
            margin-bottom: 10px;
        }
        
        .subtitle {
            color: #7f8c8d;
            font-size: 1.2rem;
        }
        
        .card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            padding: 25px;
            margin-bottom: 25px;
        }
        
        h2 {
            color: #3498db;
            margin-bottom: 20px;
            font-size: 1.8rem;
        }
        
        .tabs {
            display: flex;
            margin-bottom: 20px;
            border-bottom: 2px solid #eee;
        }
        
        .tab {
            padding: 12px 25px;
            cursor: pointer;
            font-weight: 600;
            color: #7f8c8d;
            transition: all 0.3s;
        }
        
        .tab.active {
            color: #3498db;
            border-bottom: 3px solid #3498db;
        }
        
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #2c3e50;
        }
        
        textarea, input[type="text"], input[type="file"] {
            width: 100%;
            padding: 15px;
            border: 2px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s;
        }
        
        textarea {
            min-height: 150px;
            resize: vertical;
        }
        
        textarea:focus, input:focus {
            border-color: #3498db;
            outline: none;
        }
        
        .file-upload {
            position: relative;
            display: inline-block;
            width: 100%;
        }
        
        .file-upload-label {
            display: block;
            padding: 15px;
            background: #f8f9fa;
            border: 2px dashed #ddd;
            border-radius: 8px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .file-upload-label:hover {
            border-color: #3498db;
            background: #e3f2fd;
        }
        
        .file-name {
            margin-top: 10px;
            font-size: 14px;
            color: #7f8c8d;
        }
        
        .btn {
            display: inline-block;
            background: #3498db;
            color: white;
            border: none;
            padding: 15px 28px;
            font-size: 16px;
            font-weight: 600;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
            width: 100%;
            margin-top: 10px;
        }
        
        .btn:hover {
            background: #2980b9;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }
        
        .btn-copy {
            background: #2ecc71;
            margin-top: 15px;
        }
        
        .btn-copy:hover {
            background: #27ae60;
        }
        
        .result {
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
            text-align: center;
        }
        
        .success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .text-content {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-top: 20px;
            white-space: pre-wrap;
            font-family: monospace;
        }
        
        .info-box {
            background: #e3f2fd;
            border-left: 4px solid #3498db;
            padding: 15px;
            margin: 20px 0;
            border-radius: 0 8px 8px 0;
        }
        
        .code-display {
            background: #2c3e50;
            color: white;
            padding: 15px;
            border-radius: 8px;
            text-align: center;
            font-size: 24px;
            font-weight: bold;
            letter-spacing: 3px;
            margin: 20px 0;
            white-space: pre-wrap; /* 修复：添加自动换行 */
            word-break: break-word; /* 修复：长单词自动换行 */
        }
        
        footer {
            text-align: center;
            margin-top: 30px;
            color: #7f8c8d;
            font-size: 0.9rem;
        }
        
        @media (max-width: 600px) {
            .container {
                padding: 15px;
            }
            
            h1 {
                font-size: 2rem;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>匿名口令分享系统</h1>
            <p class="subtitle">像取快递一样简单分享文本和文件</p>
        </header>
        
        <?php if (isset($_SESSION['error'])): ?>
            <div class="result error">
                <p><?php echo $_SESSION['error']; unset($_SESSION['error']); ?></p>
            </div>
        <?php endif; ?>
        
        <?php if (isset($_SESSION['success'])): ?>
            <div class="result success">
                <p><?php echo $_SESSION['success']; ?></p>
                
                <?php if (isset($_SESSION['code'])): ?>
                    <div class="code-display">
                        <?php echo $_SESSION['code']; ?>
                    </div>
                    <button class="btn btn-copy" onclick="copyCode()">复制提取码</button>
                <?php endif; ?>
            </div>
            <?php unset($_SESSION['success'], $_SESSION['code']); ?>
        <?php endif; ?>
        
        <div class="card">
            <h2>分享内容</h2>
            
            <div class="tabs">
                <div class="tab active" data-tab="text">分享文本</div>
                <div class="tab" data-tab="file">分享文件</div>
            </div>
            
            <form method="post" enctype="multipart/form-data" id="shareForm">
                <input type="hidden" name="type" id="shareType" value="text">
                
                <div class="tab-content active" id="text-tab">
                    <div class="form-group">
                        <label for="text_content">输入要分享的文本内容</label>
                        <textarea name="text_content" id="text_content" placeholder="在此输入文本内容..."></textarea>
                    </div>
                </div>
                
                <div class="tab-content" id="file-tab">
                    <div class="form-group">
                        <label for="file_upload">选择要分享的文件</label>
                        <div class="file-upload">
                            <label class="file-upload-label" for="file_upload">
                                <span id="file-label">点击或拖放文件到此处</span>
                                <input type="file" name="file_upload" id="file_upload" style="display: none;">
                            </label>
                            <div class="file-name" id="file-name">未选择文件</div>
                        </div>
                    </div>
                    <div class="info-box">
                        <p>最大文件大小: <?php echo formatFileSize(MAX_FILE_SIZE); ?></p>
                        <p>文件将在24小时后自动删除</p>
                    </div>
                </div>
                
                <button type="submit" class="btn">生成提取码</button>
            </form>
        </div>
        
        <div class="card">
            <h2>提取内容</h2>
            <form method="get" id="retrieveForm">
                <div class="form-group">
                    <label for="retrieve-code">输入提取码</label>
                    <input type="text" name="code" id="retrieve-code" placeholder="输入6位提取码" required maxlength="6">
                </div>
                <button type="submit" class="btn">提取内容</button>
            </form>
            
            <?php if (isset($_SESSION['retrieved_text'])): ?>
                <div class="code-display">
                    <?php echo htmlspecialchars($_SESSION['retrieved_text']); ?>
                </div>
                <?php unset($_SESSION['retrieved_text']); ?>
            <?php endif; ?>
        </div>
        
        <div class="info-box">
            <h3>使用说明</h3>
            <p>1. 选择分享类型（文本或文件）并提交</p>
            <p>2. 系统会生成一个6位提取码</p>
            <p>3. 将提取码分享给接收者</p>
            <p>4. 接收者输入提取码即可获取内容</p>
            <p>5. 所有内容将在24小时后自动删除</p>
        </div>
        
        <footer>
            <p>匿名口令分享系统 &copy; <?php echo date('Y'); ?></p>
        </footer>
    </div>
    
    <script>
        // 标签切换功能
        document.querySelectorAll('.tab').forEach(tab => {
            tab.addEventListener('click', () => {
                // 移除所有活动标签
                document.querySelectorAll('.tab').forEach(t => {
                    t.classList.remove('active');
                });
                
                // 隐藏所有内容
                document.querySelectorAll('.tab-content').forEach(content => {
                    content.classList.remove('active');
                });
                
                // 激活当前标签
                tab.classList.add('active');
                
                // 显示对应内容
                const tabId = tab.getAttribute('data-tab');
                document.getElementById(tabId + '-tab').classList.add('active');
                document.getElementById('shareType').value = tabId;
            });
        });
        
        // 文件上传显示文件名
        document.getElementById('file_upload').addEventListener('change', function(e) {
            const fileName = e.target.files[0] ? e.target.files[0].name : '未选择文件';
            document.getElementById('file-name').textContent = fileName;
        });
        
        // 拖放文件功能
        const dropArea = document.querySelector('.file-upload-label');
        
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, preventDefaults, false);
        });
        
        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }
        
        ['dragenter', 'dragover'].forEach(eventName => {
            dropArea.addEventListener(eventName, highlight, false);
        });
        
        ['dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, unhighlight, false);
        });
        
        function highlight() {
            dropArea.style.borderColor = '#3498db';
            dropArea.style.backgroundColor = '#e3f2fd';
        }
        
        function unhighlight() {
            dropArea.style.borderColor = '#ddd';
            dropArea.style.backgroundColor = '#f8f9fa';
        }
        
        dropArea.addEventListener('drop', handleDrop, false);
        
        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            
            if (files.length) {
                document.getElementById('file_upload').files = files;
                document.getElementById('file-name').textContent = files[0].name;
            }
        }
        
        // 复制提取码功能
        function copyCode() {
            const code = document.querySelector('.code-display').textContent;
            navigator.clipboard.writeText(code).then(() => {
                alert('提取码已复制到剪贴板: ' + code);
            }).catch(err => {
                console.error('复制失败:', err);
            });
        }
        
        // 表单验证修复
        document.getElementById('shareForm').addEventListener('submit', function(e) {
            const type = document.getElementById('shareType').value;
            
            if (type === 'text') {
                const textArea = document.getElementById('text_content');
                if (!textArea.value.trim()) {
                    e.preventDefault();
                    alert('请输入文本内容');
                    textArea.focus();
                }
            } else if (type === 'file') {
                const fileInput = document.getElementById('file_upload');
                if (!fileInput.files || fileInput.files.length === 0) {
                    e.preventDefault();
                    alert('请选择要上传的文件');
                    fileInput.click();
                }
            }
        });
        
        // 输入框自动大写和粘贴修复
        const retrieveCodeInput = document.getElementById('retrieve-code');
        
        // 修复：粘贴时处理内容
        retrieveCodeInput.addEventListener('paste', function(e) {
            // 允许粘贴操作
            const pastedText = (e.clipboardData || window.clipboardData).getData('text');
            // 移除所有非字母数字字符
            const cleanedText = pastedText.replace(/[^a-zA-Z0-9]/g, '');
            // 截取前6个字符
            const finalText = cleanedText.substring(0, 6).toUpperCase();
            
            // 设置输入框值
            this.value = finalText;
            
            // 阻止默认粘贴行为
            e.preventDefault();
        });
        
        // 修复：输入时处理内容
        retrieveCodeInput.addEventListener('input', function(e) {
            // 移除所有非字母数字字符
            this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
            // 截取前6个字符
            this.value = this.value.substring(0, 6).toUpperCase();
        });
    </script>
</body>
</html>